package co.chonghao.ch_kuaichong_user.ui.activitys;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import co.chonghao.ch_kuaichong_user.R;
import co.chonghao.ch_kuaichong_user.app.App;
import co.chonghao.ch_kuaichong_user.base.BaseActivity;
import co.chonghao.ch_kuaichong_user.utils.DialogUtil;
import co.chonghao.ch_kuaichong_user.utils.InputValidator;
import co.chonghao.ch_kuaichong_user.utils.LogUtils;
import co.chonghao.ch_kuaichong_user.utils.TitleBuilder;
import co.chonghao.ch_kuaichong_user.utils.ToastUtil;

/**
 * Created by admin on 2017/8/1.
 */

public class LoginActivity extends BaseActivity {


    @BindView(R.id.title_right_imageview)
    ImageView titleRightImageview;
    @BindView(R.id.line)
    View line;
    @BindView(R.id.title_bar)
    RelativeLayout titleBar;
    @BindView(R.id.etPhone)
    EditText etPhone;
    @BindView(R.id.etCode)
    EditText etCode;
    @BindView(R.id.tvGetCode)
    TextView tvGetCode;
    @BindView(R.id.tvLogin)
    TextView tvLogin;
    @BindView(R.id.llUserAgreement)
    LinearLayout llUserAgreement;
    private String validateCode;//随机生成的6位验证码
    private ProgressDialog progressDialog;
    private TimeCounter mTimeCounter = new TimeCounter(60000, 1000);

    @Override
    public void setView() {
        setContentView(R.layout.fragment_login);
        ButterKnife.bind(this);
        new TitleBuilder(this)
                .setLeftImageBack()
                .setMiddleTitleText("手机验证");
        App.getInstance().addActivity(this);
        Log.d("页面集合",App.getList().size()+"");
        App.initStaus(this);
    }

    @OnClick({R.id.tvGetCode, R.id.tvLogin, R.id.llUserAgreement})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tvGetCode:
                if (!"BINGO".equals(InputValidator.checkMobileNum(etPhone.getText().toString().trim()))) {
                    ToastUtil.showToast(InputValidator.checkMobileNum(etPhone.getText().toString().trim()));
                    return;
                }
                getRandomCode();
                mTimeCounter.start();
                break;
            case R.id.tvLogin:
//                launch(MainActivity.class);
                launch(SelectCityActivity.class);
//                if (!etCode.getText().toString().trim().equals(validateCode)) {
//                    ToastUtils.showMyToast("验证码错误，请确认后输入");
//                    return;
//                }
//                /**15分钟验证码过期*/
//                if (System.currentTimeMillis() - expireTime > 15 * 60 * 1000) {
//                    ToastUtil.showToast("验证码过期");
//                    return;
//                }
//                regist(etPhone.getText().toString().trim(), etCode.getText().toString().trim(),
//                        , "02");
                break;
            case R.id.llUserAgreement:
                //launch(WebViewActivity.class, "agreement", "fuwu");
                break;
        }
    }

    @Override
    public void init() {
        progressDialog = DialogUtil.getInstance(LoginActivity.this, "请稍等···").getDialog();
    }

    /**
     * 获取验证码
     *
     * @param mobile       手机号
     * @param validateCode 随机生成的6位验证码
     */
    private long expireTime;//获取验证码的时间

//    public void getCode(String mobile, String validateCode) {
//        RequestParams params = new RequestParams();
//        params.put("mobile", mobile);
//        params.put("validateCode", validateCode);
//        AsHttpClient.httpPost(URLConstants.SEND_CODE, params,
//                new AsHttpClient.OnResponseListener() {
//                    @Override
//                    public void onResponse(String responseValue) {
//                        VerificationCodeBean result = resolveResponse(responseValue, VerificationCodeBean.class);
//                        if (result != null) {
//                            if (result.getCode().equals("00")) {
//                                mTimeCounter.start();
//                                expireTime = System.currentTimeMillis();
//                            }
//                            ToastUtils.showMyToast(result.getMessage());
//                        }
//                    }
//                });
//    }

    /**
     * 注册
     *
     * @param mobile       手机号
     * @param safeCode     验证码
     * @param pwd          密码
     * @param signupSource 注册来源 （01：ios、02：android）
     */
//    public void regist(final String mobile, String safeCode, final String pwd, String signupSource) {
//        RequestParams params = new RequestParams();
//        params.put("mobile", mobile);
//        params.put("safeCode", safeCode);
//        params.put("pwd", SignUtil.Md5(pwd));
//        params.put("signupSource", signupSource);
//        AsHttpClient.httpPost(URLConstants.REGIST, params, new AsHttpClient.OnResponseListener() {
//            @Override
//            public void onResponse(String responseValue) {
//                RegistBean bean = resolveResponse(responseValue, RegistBean.class);
//                if (bean != null) {
//                    if (bean.getCode().equals("00")) {
//                        progressDialog.show();
//                        LoginByPhone(mobile, pwd, "02");
//                    }
//                    ToastUtils.showMyToast(bean.getMessage());
//                }
//
//            }
//        });
//    }

    /**
     * @param mobile      手机号
     * @param pwd         密码
     * @param loginSource 登录来源(01ios、02android)
     */
//    public void LoginByPhone(String mobile, String pwd, String loginSource) {
//        String registrationID = JPushInterface.getRegistrationID(context);
//        RequestParams params = new RequestParams();
//        params.put("mobile", mobile);
//        params.put("pwd", SignUtil.Md5(pwd));
//        params.put("loginSource", loginSource);
//        params.put("registrationID", registrationID);
//        AsHttpClient.httpPost(URLConstants.USER_LOGIN, params, new AsHttpClient.OnResponseListener() {
//            @Override
//            public void onResponse(String responseValue) {
//                if (progressDialog != null)
//                    progressDialog.dismiss();
//
//                UserBean result = resolveResponse(responseValue, UserBean.class);
//                if (result != null) {
//                    if (result.getCode().equals("00")) {
//                        //sp保存用户信息
//                        SpUtils.saveUser(RegistActivity.this, result);
//                        App.user = result.getData();
//                        final String userId = String.valueOf(App.user.getUserId());
//                        //Jpush别名注册
//                        JPushInterface.setAlias(context, userId, new TagAliasCallback() {
//                            @Override
//                            public void gotResult(int i, String s, Set<String> set) {
//                                LogUtil.loge("状态码" + i + "别名" + userId);
//                            }
//                        });
//                        App.token = result.getData().getToken();
//                        if (result.getData().getLoginTimes() == 1) {
//                            launch(RealNameAuthenticationActivity.class);
//                            finish();
//                        } else {
//                            launch(MainActivity.class);
//                            finish();
//                        }
//                        /***/
//                    } else if (result.getCode().equals("09") || result.getCode().equals("08")) {
//                        ToastUtils.showWarningToast(result.getMessage(), 1);
//                    } else ToastUtils.showMyToast(result.getMessage());
//                }
//            }
//        });
//    }

    /**
     * 生成随机验证码并发送给服务器
     */
    public void getRandomCode() {
        //获取随机验证码
        StringBuilder sb = new StringBuilder();
        Random rand = new Random();
        for (int i = 0; i < 6; i++) {
            sb.append(rand.nextInt(10));
        }
        validateCode = sb.toString();
        LogUtils.info(validateCode);
       // getCode(etPhone.getText().toString().trim(), validateCode);
    }

    @Override

    protected void onDestroy() {
        mTimeCounter.cancel();
        super.onDestroy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }


    @Override
    public void onBackPressed() {

        finish();
    }

    /**
     * 倒计时
     */
    class TimeCounter extends CountDownTimer {


        public TimeCounter(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvGetCode.setTextColor(getResources().getColor(R.color.text_gray));
            tvGetCode.setText(String.format(getResources().getString(R.string.reg_get_code_countdown), millisUntilFinished / 1000));
            tvGetCode.setClickable(false);
        }

        @Override
        public void onFinish() {
            tvGetCode.setTextColor(getResources().getColor(R.color.text_orange));
            tvGetCode.setText("获取验证码");
            tvGetCode.setClickable(true);
        }
    }
}
